//
//  PageControlView.swift
//  TimMusic
//
//  Created by nkl on 2024/10/12.
//

import Foundation
import UIKit

class PageControlView: UIView {
    // MARK: Properties

    var preferences = Preferences() {
        didSet {
            setNeedsDisplay()
        }
    }

    var numberOfPages: Int = 0 {
        didSet {
            setNeedsDisplay()
        }
    }

    var currentPage: Int = 0 {
        didSet {
            setNeedsDisplay()
        }
    }

    // MARK: Life cycle

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setNeedsDisplay()
    }

    override func draw(_ rect: CGRect) {
        guard numberOfPages > 0 else {
            return
        }
        drawDots(rect: rect)
    }

    override var intrinsicContentSize: CGSize {
        CGSize(
            width: CGFloat(numberOfPages) * preferences.dotWidth + (CGFloat(numberOfPages) - 1) * preferences.gapSize + preferences.currentDotBorderWidth * 2,
            height: preferences.dotHeight + preferences.currentDotBorderWidth * 2
        )
    }

    // MARK: Private functions

    private func commonInit() {
        backgroundColor = .clear
    }

    private func drawDots(rect: CGRect) {
        for index in 0 ..< numberOfPages {
            // 计算每个矩形的位置
            let xPosition = preferences.currentDotBorderWidth + CGFloat(index) * (preferences.gapSize + preferences.dotWidth)
            let yPosition = (rect.height - preferences.dotHeight) / 2 // 垂直居中
            
            let dotRect = CGRect(
                x: xPosition,
                y: yPosition,
                width: preferences.dotWidth,
                height: preferences.dotHeight
            )
            
            let path = UIBezierPath(rect: dotRect) // 创建矩形路径
            
            if index == currentPage {
                // 设置当前页的边框宽度
                path.lineWidth = preferences.currentDotBorderWidth
                preferences.currentColor.setFill()
                path.fill()
            } else {
                // 其他页的颜色和透明度
                preferences.color.withAlphaComponent(preferences.dimFactor).setFill()
                path.fill()
            }
        }
    }

}

extension PageControlView {
    struct Preferences {
        // MARK: Properties
        var currentColor : UIColor = .white
        var color: UIColor = .white
        var dimFactor: CGFloat = 0.57
        var dotWidth: CGFloat = 3.5
        var dotHeight: CGFloat = 3.5
        var gapSize: CGFloat = 5
        var currentDotBorderWidth: CGFloat = 3
    }
}
